package com.rest.api;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.ws.rs.BeanParam;
import javax.ws.rs.CookieParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Providers;

import org.springframework.stereotype.Component;

import com.rest.api.bean.UrlParams;

@Component
@Path("/annotation")
@Produces({ MediaType.APPLICATION_JSON })
public class AnnotationApi {

	@GET
	@Path("/china/{province:.+}/{city:\\w+}")
	public UrlParams bean(@BeanParam UrlParams params) {
		System.out.println(params.getAcceptParam());
		return params;
	}
	
	@GET
	@Path("/context/{province:.+}/{city:\\w+}")
	public Map<String, Object> context(
            @Context final Application application,
            @Context final Request request,
            @Context final Providers provider,
            @Context final UriInfo uriInfo,
            @Context final HttpHeaders headers){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("path", uriInfo.getPath());
		map.put("PathParames", iterating(uriInfo.getPathParameters()));
		map.put("QueryParames", iterating(uriInfo.getQueryParameters()));
		map.put("PathSegments", uriInfo.getPathSegments());
		map.put("RequestHeaders", iterating(headers.getRequestHeaders()));
		map.put("Cookies", headers.getCookies());
		return map;
	}
	
	@GET
	@Path("/cookie")
	public Map<String,Object> CookieParam(
			@CookieParam("CKFinder_Path") final String CKFinder_Path){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("CKFinder_Path", CKFinder_Path);
		return map;
	}

	private Map<String, Object> iterating(final MultivaluedMap<String, String> pathMap) {
		Map<String, Object> map = new HashMap<String, Object>();
        final Iterator<Entry<String, List<String>>> i = pathMap.entrySet().iterator();
        while (i.hasNext()) {
        	StringBuffer buf = new StringBuffer();
            final Entry<String, List<String>> e = i.next();
            final String k = e.getKey();
            final List<String> vList = e.getValue();
            for (final String v : vList) {
                buf.append(v).append(" ");
            }
            map.put(k, buf);
        }
        return map;
    }
	
}
